//
//  AppDelegate+pushHandle.m
//  DevDemo
//
//  Created by wsj2015 on 16/8/4.
//  Copyright © 2016年 chengwei06. All rights reserved.
//

#import "AppDelegate+pushHandle.h"
#import "BPush.h"

#import "EBForeNotification.h"
#import "WCBaiduPushBindHelp.h"
#import "BTTabBarVC.h"
#import "BTNavigationContrller.h"
#import "CWQ_MessageVC.h"

//#import "HELMeetingInfo.h"
//#import "HELTabBarVC.h"
static BOOL isBackGroundActivateApplication;
@implementation AppDelegate (pushHandle)


- (BOOL)BPushApplicationWith:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wsj_logcalNotiClick:) name:EBBannerViewDidClick object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reBindBPush) name:LoginSuccessNotification object:nil];
    
    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
#warning 测试 开发环境 时需要修改BPushMode为BPushModeDevelopment 需要修改Apikey为自己的Apikey
    
    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
    NSString *key = @"pUDwY8F5kFG3lVlm7LFKxXk2";
    
    BPushMode mode;
#ifdef DEBUG

    mode = BPushModeDevelopment;
#else
    
    mode =BPushModeProduction;
    
#endif
    
    [BPush registerChannel:launchOptions apiKey:key pushMode:mode withFirstAction:@"打开" withSecondAction:@"回复" withCategory:@"test" useBehaviorTextInput:YES isDebug:YES];
    
    // 禁用地理位置推送 需要再绑定接口前调用。
    
    [BPush disableLbs];
    
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        [BPush handleNotification:userInfo];
    }
#if TARGET_IPHONE_SIMULATOR
    Byte dt[32] = {0xc6, 0x1e, 0x5a, 0x13, 0x2d, 0x04, 0x83, 0x82, 0x12, 0x4c, 0x26, 0xcd, 0x0c, 0x16, 0xf6, 0x7c, 0x74, 0x78, 0xb3, 0x5f, 0x6b, 0x37, 0x0a, 0x42, 0x4f, 0xe7, 0x97, 0xdc, 0x9f, 0x3a, 0x54, 0x10};
    [self application:application didRegisterForRemoteNotificationsWithDeviceToken:[NSData dataWithBytes:dt length:32]];
#endif
    //角标清0
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    return YES;
    
}

- (void)reBindBPush{

    [WCBaiduPushBindHelp bindToService];
}
//本地通知被点击
- (void)wsj_logcalNotiClick:(NSNotification*)noti{
    // 测试本地通知
//    [self performSelector:@selector(testLocalNotifi) withObject:nil afterDelay:.2];
    
    
    [self gotoMeetingInforVC];
    

}

- (void)testLocalNotifi
{

    UILocalNotification * localnoti = [[UILocalNotification alloc]init];
    localnoti.userInfo = @{@"isLocal":@(1)};
    localnoti.alertBody = @"有新通知!";
    // 获取整个应用程序引用
    UIApplication *applicaiton = [UIApplication sharedApplication];
    //    scheduleLocalNotification
    
    localnoti.applicationIconBadgeNumber = 1;
    
    [applicaiton presentLocalNotificationNow:localnoti];
    
    
    
}
#pragma mark -********** ios7.0之前 **********
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    // App 收到推送的通知
    [BPush handleNotification:userInfo];
    // 应用在前台，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive) {
        WSJLog(@"acitve ");
       
        [EBForeNotification handleRemoteNotification:userInfo soundID:1312];
     
    }
    //杀死状态下，直接跳转到跳转页面。
    if (application.applicationState == UIApplicationStateInactive && !isBackGroundActivateApplication)
    {
        
         [self gotoMeetingInforVC];
        WSJLog(@"applacation is unactive ===== %@",userInfo);
        
    }
    // 应用在后台。当后台设置aps字段里的 content-available 值为 1 并开启远程通知激活应用的选项
    if (application.applicationState == UIApplicationStateBackground) {
        WSJLog(@"background is Activated Application ");
        // 此处可以选择激活应用提前下载邮件图片等内容。
        isBackGroundActivateApplication = YES;
         [self gotoMeetingInforVC];
    }
    

    
}
#pragma mark -********** ios7.0之后面 **********
// 此方法是 用户点击了通知，应用在前台 或者开启后台并且应用在后台 时调起********** iOS7.0之后 background
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    completionHandler(UIBackgroundFetchResultNewData);
    // 打印到日志 textView 中
    WSJLog(@"********** iOS7.0之后 background **********");
    // 应用在前台，不跳转页面，让用户选择。
    if (application.applicationState == UIApplicationStateActive) {

        [EBForeNotification handleRemoteNotification:userInfo soundID:1312];
       

    }
    //杀死状态下，直接跳转到跳转页面。
    if (application.applicationState == UIApplicationStateInactive && !isBackGroundActivateApplication)
    {
 
        
         [self gotoMeetingInforVC];
        WSJLog(@"applacation is unactive ===== %@",userInfo);
    
    }
    // 应用在后台。当后台设置aps字段里的 content-available 值为 1 并开启远程通知激活应用的选项
    if (application.applicationState == UIApplicationStateBackground) {
        WSJLog(@"background is Activated Application ");
        // 此处可以选择激活应用提前下载邮件图片等内容。
        isBackGroundActivateApplication = YES;
        [self gotoMeetingInforVC];
    }

    
    WSJLog(@"%@",userInfo);
}

- (void)gotoMeetingInforVC{

    
  
    
    if (!BT_USERID) {
        return;
    }
        BTTabBarVC *tbc = (BTTabBarVC *)[[[UIApplication sharedApplication] delegate] window].rootViewController;
    BTNavigationContrller *nav = tbc.viewControllers.lastObject;
    
    tbc.selectedIndex = 3;
    
    [nav.viewControllers enumerateObjectsUsingBlock:^(__kindof UIViewController * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ( [obj isKindOfClass:[CWQ_MessageVC class]]) {
            [nav popToViewController:obj animated:YES];
            return ;
        }
        if (idx == nav.viewControllers.count -1) {
            [nav pushViewController:[CWQ_MessageVC new] animated:YES];
        }
        
    }];
    
}


// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
    [application registerForRemoteNotifications];
    
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    WSJLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {

        
        // 网络错误
        if (error) {
            return ;
        }
        if (result) {
            // 确认绑定成功
            if ([result[@"error_code"]intValue]!=0) {
                return;
            }
            // 获取channel_id
            NSString *myChannel_id = [BPush getChannelId];
            WSJLog(@"==%@",myChannel_id);
            
            [BPush listTagsWithCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    WSJLog(@"result ============== %@",result);
                }
                 [WCBaiduPushBindHelp bindToService];
            }];
            [BPush setTag:@"Mytag" withCompleteHandler:^(id result, NSError *error) {
                if (result) {
                    WSJLog(@"设置tag成功");
                }
            }];
        }
    }];
    
    // 打印到日志 textView 中
//    [self.viewController addLogString:[NSString stringWithFormat:@"Register use deviceToken : %@",deviceToken]];
    
    
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    WSJLog(@"DeviceToken 获取失败，原因：%@",error);
}




#pragma mark -本地通知
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
//    WSJLog(@"接收本地通知啦！！！");
//    
//    //应用在前台
//    if (application.applicationState == UIApplicationStateActive && !isBackGroundActivateApplication) {
//        UIAlertView *aler =[[UIAlertView alloc] initWithTitle:@"王苏进测试" message:@"这是程序在前台点击本地通知进来的" delegate:nil cancelButtonTitle:@"哦😢" otherButtonTitles: nil];
//        [aler show];
//      
//    }
//
//    // 应用在后台。当后台设置aps字段里的 content-available 值为 1 并开启远程通知激活应用的选项
//    if (application.applicationState == UIApplicationStateBackground) {
//        WSJLog(@"background is Activated Application ");
//        // 此处可以选择激活应用提前下载邮件图片等内容。
//        isBackGroundActivateApplication = YES;
//        UIAlertView *alertView =[[UIAlertView alloc]initWithTitle:@"收到一条消息" message:@"这是程序挂起状态下本地通知被点击" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//        [alertView show];
//    }
// 
    
//    [BPush showLocalNotificationAtFront:notification identifierKey:nil];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
//        SkipViewController *skipCtr = [[SkipViewController alloc]init];
        // 根视图是nav 用push 方式跳转
//        [_tabBarCtr.selectedViewController pushViewController:skipCtr animated:YES];
        /*
         // 根视图是普通的viewctr 用present跳转
         [_tabBarCtr.selectedViewController presentViewController:skipCtr animated:YES completion:nil]; */
    }
}

@end
